<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
          <el-form-item label="订单编号" prop="orderNo">
            <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="学生姓名" prop="studentName">
            <el-input v-model="queryParams.studentName" placeholder="请输入学生姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="班级名称" prop="className">
            <el-input v-model="queryParams.className" placeholder="请输入班级名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="支付状态" prop="payStatus">
            <el-select v-model="queryParams.payStatus" placeholder="请选择支付状态" clearable>
              <el-option v-for="dict in service_pay_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="订阅时间" style="width: 308px">
            <el-date-picker
              v-model="dateRangeSubscribeTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="4">
            <span>已订阅人数：{{ subscribeStat.subscribedNum }}</span>
          </el-col>
          <el-col :span="4">
            <span>总金额：{{ subscribeStat.totalAmount }}元</span>
          </el-col>
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['office:serviceSubscribe:remove']">删除</el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['office:serviceSubscribe:export']">导出</el-button>-->
          <!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table height="calc(100vh - 410px)" v-loading="loading" :data="serviceSubscribeList" @selection-change="handleSelectionChange">
        <el-table-column label="订单编号" align="center" prop="orderNo" />
        <el-table-column label="学生姓名" align="center" prop="studentName" />
        <el-table-column label="班级名称" align="center" prop="className" />
        <el-table-column label="支付手机号" align="center" prop="payPhone" />
        <el-table-column label="购买服务" align="center" prop="serviceName" />
        <el-table-column label="支付金额（元）" align="center" prop="payAmount" />
        <el-table-column label="支付时间" align="center" prop="payTime" width="180">
          <template #default="scope">
            <span>{{ scope.row.payTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="支付状态" align="center" prop="payStatus">
          <template #default="scope">
            <dict-tag :options="service_pay_status" :value="scope.row.payStatus" />
          </template>
        </el-table-column>
        <el-table-column label="退订时间" align="center" prop="unsubscribeTime" width="180">
          <template #default="scope">
            <span>{{ scope.row.unsubscribeTime }}</span>
          </template>
        </el-table-column>
        <!--        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
        <!--          <template #default="scope">-->
        <!--            <el-tooltip content="修改" placement="top">-->
        <!--              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['office:serviceSubscribe:edit']"></el-button>-->
        <!--            </el-tooltip>-->
        <!--            <el-tooltip content="删除" placement="top">-->
        <!--              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['office:serviceSubscribe:remove']"></el-button>-->
        <!--            </el-tooltip>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改服务包订阅对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="serviceSubscribeFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="服务id" prop="serviceId">
          <el-input v-model="form.serviceId" placeholder="请输入服务id" />
        </el-form-item>
        <el-form-item label="服务名称" prop="serviceName">
          <el-input v-model="form.serviceName" placeholder="请输入服务名称" />
        </el-form-item>
        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="学生id" prop="studentId">
          <el-input v-model="form.studentId" placeholder="请输入学生id" />
        </el-form-item>
        <el-form-item label="学生姓名" prop="studentName">
          <el-input v-model="form.studentName" placeholder="请输入学生姓名" />
        </el-form-item>
        <el-form-item label="班级id" prop="classId">
          <el-input v-model="form.classId" placeholder="请输入班级id" />
        </el-form-item>
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级名称" />
        </el-form-item>
        <el-form-item label="支付手机号" prop="payPhone">
          <el-input v-model="form.payPhone" placeholder="请输入支付手机号" />
        </el-form-item>
        <el-form-item label="支付金额" prop="payAmount">
          <el-input v-model="form.payAmount" placeholder="请输入支付金额" />
        </el-form-item>
        <el-form-item label="支付时间" prop="payTime">
          <el-date-picker clearable v-model="form.payTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择支付时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="支付状态" prop="payStatus">
          <el-select v-model="form.payStatus" placeholder="请选择支付状态">
            <el-option v-for="dict in service_pay_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订阅时间" prop="subscribeTime">
          <el-date-picker clearable v-model="form.subscribeTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择订阅时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="退订时间" prop="unsubscribeTime">
          <el-date-picker clearable v-model="form.unsubscribeTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择退订时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ServiceSubscribe" lang="ts">
import {
  listServiceSubscribe,
  getServiceSubscribe,
  delServiceSubscribe,
  addServiceSubscribe,
  updateServiceSubscribe
} from '@/api/office/service/subscribe';
import { ServiceSubscribeVO, ServiceSubscribeQuery, ServiceSubscribeForm } from '@/api/office/service/subscribe/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { service_pay_status } = toRefs<any>(proxy?.useDict('service_pay_status'));

const serviceSubscribeList = ref<ServiceSubscribeVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRangeSubscribeTime = ref<[DateModelType, DateModelType]>(['', '']);
const subscribeStat = ref({ subscribedNum: 0, totalAmount: 0 });
const queryFormRef = ref<ElFormInstance>();
const serviceSubscribeFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ServiceSubscribeForm = {
  id: undefined,
  serviceId: undefined,
  serviceName: undefined,
  orderNo: undefined,
  studentId: undefined,
  studentName: undefined,
  classId: undefined,
  className: undefined,
  payPhone: undefined,
  payAmount: undefined,
  payTime: undefined,
  payStatus: undefined,
  subscribeTime: undefined,
  unsubscribeTime: undefined
};
const data = reactive<PageData<ServiceSubscribeForm, ServiceSubscribeQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: undefined,
    studentName: undefined,
    className: undefined,
    payStatus: undefined,
    params: {
      subscribeTime: undefined
    }
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    serviceId: [{ required: true, message: '服务id不能为空', trigger: 'blur' }],
    serviceName: [{ required: true, message: '服务名称不能为空', trigger: 'blur' }],
    orderNo: [{ required: true, message: '订单编号不能为空', trigger: 'blur' }],
    studentId: [{ required: true, message: '学生id不能为空', trigger: 'blur' }],
    studentName: [{ required: true, message: '学生姓名不能为空', trigger: 'blur' }],
    classId: [{ required: true, message: '班级id不能为空', trigger: 'blur' }],
    className: [{ required: true, message: '班级名称不能为空', trigger: 'blur' }],
    payPhone: [{ required: true, message: '支付手机号不能为空', trigger: 'blur' }],
    payAmount: [{ required: true, message: '支付金额不能为空', trigger: 'blur' }],
    payTime: [{ required: true, message: '支付时间不能为空', trigger: 'blur' }],
    payStatus: [{ required: true, message: '支付状态不能为空', trigger: 'change' }],
    subscribeTime: [{ required: true, message: '订阅时间不能为空', trigger: 'blur' }],
    unsubscribeTime: [{ required: true, message: '退订时间不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询服务包订阅列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, dateRangeSubscribeTime.value, 'SubscribeTime');
  const res = await listServiceSubscribe(queryParams.value);
  serviceSubscribeList.value = res.rows;
  total.value = res.total;
  subscribeStat.value = res.stat;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  serviceSubscribeFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeSubscribeTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ServiceSubscribeVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加服务包订阅';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ServiceSubscribeVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getServiceSubscribe(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改服务包订阅';
};

/** 提交按钮 */
const submitForm = () => {
  serviceSubscribeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateServiceSubscribe(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addServiceSubscribe(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ServiceSubscribeVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除服务包订阅编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delServiceSubscribe(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'office/serviceSubscribe/export',
    {
      ...queryParams.value
    },
    `serviceSubscribe_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
